print("\r\n-----------------------------\r\n DayTime_Micor\r\n-----------------------------\r\n")

-----------------------------wifi------------------------------
wifi.setmode(wifi.STATIONAP)
--wifi.ap.config({ssid="ESP8266", auth=wifi.OPEN})
--enduser_setup.manual(true)
enduser_setup.start(
  function()
    print("enduser_setup Connected to WiFi as:" .. wifi.sta.getip())
  end,
  function(err, str)
    print("enduser_setup: Err #" .. err .. ": " .. str)
  end
)
--[[
configwifissid = "ChinaNet-PEtw";
configwifipwd="d9aprfdw";
clientid = wifi.sta.getmac()

wifi.setmode(wifi.STATIONAP)
apcfg={}
apcfg.ssid=configwifissid
apcfg.pwd=configwifipwd
wifi.sta.config(apcfg)
wifi.sta.autoconnect(1)
]]
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T)
    print("eventmon.STA_DISCONNECTED")
    disp:clearBuffer()
    disp:setFont(u8g2.font_unifont_t_symbols)
    disp:drawFrame(0, 0, 128, 64)
    disp:drawStr(12, 4, "DayTime_Micor")
    disp:drawLine(8, 20, 120, 20)
    disp:drawStr(4, 32, "Wifi connect...")
    disp:sendBuffer()
end)

wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T)
    print("eventmon.STA_GOT_IP IP: "..T.IP)
    disp:clearBuffer()
    disp:setFont(u8g2.font_unifont_t_symbols)
    disp:drawFrame(0, 0, 128, 64)
    disp:drawStr(4, 32,T.IP)
    disp:sendBuffer()
end)


------------------------------------OLED----------------------------
local function init_oled()
    local sda = 2
    local scl = 5
    local sla = 0x3c

    i2c.setup(0, sda, scl, i2c.SLOW)
    disp = u8g2.ssd1306_i2c_128x64_noname(0, sla)
    disp:setFlipMode(0)
    disp:setFont(u8g2.font_unifont_t_symbols)
    disp:setFontRefHeightExtendedText()
    --disp:setDrawColor(1)
    disp:setFontPosTop()
    --disp:setFontDirection(0)
    
    disp:clearBuffer()
    disp:drawFrame(0, 0, 128, 64)
    disp:drawStr(12, 4, "DayTime_Micor")
    disp:drawLine(8, 20, 120, 20)
    disp:drawStr(4, 32, "Wifi connect...")
    disp:sendBuffer()
end

init_oled()

--------------------------------------OLED_SHOW-----------------------------------
local current_day = "2022-01-01"
local current_month = 00
local current_today = 00
local current_time = "00:00:00"
local current_time_hr_min = "00:00"
local current_time_hr = "00"
local current_time_min = "00"
local current_time_s = "00"

oled_show_index = 0
oled_show_index_max = 4

local function oled_show()
    print(current_day.."  "..current_time)
    if (wifi.sta.getip() ~= nil) then
        if (get_ntp_update_flag() == 1) then    
            disp:clearBuffer()
            
            if(oled_show_index == 0)then               
                disp:setFont(u8g2.font_unifont_t_symbols)
                disp:drawStr(0, 0,  " DAY "..current_day)
                disp:drawLine(5, 20, 123, 20)
                disp:drawLine(5, 55, 123, 55)
                disp:setFont(u8g2.font_timB24_tf)
                disp:drawStr(5, 24, current_time)
            elseif(oled_show_index == 1)then  
                disp:setFont(u8g2.font_unifont_t_symbols)
                disp:drawStr(25, 0,  current_day)
                disp:drawLine(15, 15, 113, 15)
                disp:setFont(u8g2.font_timB24_tf)
                disp:drawStr(0, 28, current_time_hr_min..":")
                disp:setFont(u8g2.font_freedoomr25_mn)
                disp:drawStr(85,28, current_time_s)
            elseif(oled_show_index == 2)then  
                disp:setFont(u8g2.font_logisoso50_tn)
                disp:drawStr(0, 5, current_time_hr)
                disp:drawStr(64, 5, current_time_min)
                disp:setFont(u8g2.font_unifont_t_symbols)
                disp:drawStr(60, 5, ":")
                disp:drawStr(60, 45, ":")
            elseif(oled_show_index == 3)then  
                --month = {"January","February","March","April","May","June","July","August","September","October","November","December"}
                disp:setFont(u8g2.font_freedoomr25_mn)
                disp:drawStr(0, 24, current_time_hr_min)
                disp:setFont(u8g2.font_unifont_t_symbols)
                disp:drawStr(25, 0,  current_day)
                disp:drawLine(25, 15, 105, 15)
                disp:drawLine(25, 16, 105, 16)
                disp:drawStr(103,30, current_time_s)
                disp:drawLine(5, 55, 93, 55)
                disp:drawLine(5, 56, 93, 56)
                disp:drawLine(5, 57, 93, 57)
                disp:drawLine(5, 58, 93, 58)
                disp:drawLine(5, 59, 93, 59)
            end

            disp:sendBuffer()
        end
    end
end
local oled_show_time = tmr.create()
oled_show_time:alarm(1000, tmr.ALARM_AUTO, oled_show)

-------------------------------NTP------------------------------------------
local NTP_SERVERS = { "ntp.aliyun.com",
                "time.asia.apple.com",
                "cn.ntp.org.cn",
                "time.windows.com",
                "cn.pool.ntp.org"
                }
local ntp_update_flag = 0

local function StpSync_OK(sec, usec, server, info)
    print('StpSync_OK', sec, usec, server)
    Timer_SyncNTP:interval(3600000)
    ntp_update_flag = 1
end

local function StpSync_Fail()
    print('StpSync_Fail')
--    Timer_SyncNTP:interval(1000)
end

local function NtpSync()
    if (wifi.sta.getip() == nil) then
        print("NtpSync wifi Connecting...")
    else
        print("NtpSync wifi Connected, IP is "..wifi.sta.getip())
        sntp.sync(NTP_SERVERS, StpSync_OK, StpSync_Fail)
    end
end

local function printTime()
    tm = rtctime.epoch2cal(rtctime.get() + 8 * 3600)
    print(string.format("%04d/%02d/%02d %02d:%02d:%02d", tm["year"], tm["mon"], tm["day"], tm["hour"], tm["min"], tm["sec"]))
    current_day = string.format("%04d/%02d/%02d", tm["year"], tm["mon"], tm["day"])
    current_month = string.format("%02d",tm["mon"])
    current_today = string.format("%02d",tm["day"])
    current_time = string.format("%02d:%02d:%02d", tm["hour"], tm["min"],tm["sec"])
    current_time_hr_min = string.format("%02d:%02d", tm["hour"], tm["min"])
    current_time_hr = string.format("%02d", tm["hour"])
    current_time_min = string.format("%02d", tm["min"])
    current_time_s = string.format("%02d", tm["sec"])
end

function get_ntp_update_flag()
    printTime()
    return ntp_update_flag
end

Timer_SyncNTP = tmr.create()
Timer_SyncNTP:register(10000, tmr.ALARM_AUTO, NtpSync)
Timer_SyncNTP:start()

Timer_Print = tmr.create()
Timer_Print:register(1000, tmr.ALARM_AUTO, printTime)
Timer_Print:start()

------------------------------KEY--------------------------------
KEY = 3
local key_press_time = 0
local key_press_event = 0
local key_mutil_count = 0

local function key_short_up_handle()
    print("key short press up")
    oled_show_index = oled_show_index+1
    if(oled_show_index == oled_show_index_max)then
        oled_show_index = 0
    end
    oled_show()
end
local function key_long_up_handle()
     print("key_long_up")
end
local function key_long_long_up_handle()
     print("key_long_long_up")
end
local function key_short_press_handle()
    print("key short press")
end
local function key_long_press_handle()
    print("key long press")
end
local function key_long_long_press_handle()
    print("key_long_long_press")
    wifi.sta.disconnect()
    node.restore()
end

gpio.mode(KEY, gpio.INPUT,gpio.PULLUP)

local key_press_time = 0
local key_press_event = 0

key_timer = tmr.create()
key_timer:alarm(10, tmr.ALARM_AUTO, function()

    if (gpio.read(KEY) == 0) then
        key_press_time = key_press_time + 1
        if(key_press_time > 500)then
            if(key_press_event ~= 3)then
                key_press_event = 3
                key_long_long_press_handle()
            end
        elseif(key_press_time > 150)then
            if(key_press_event ~= 2)then
                key_press_event = 2
                key_long_press_handle()
            end
        elseif(key_press_time > 0)then
            if(key_press_event ~= 1)then
                key_press_event = 1 
                key_short_press_handle()
            end
            
        end
    else
        if(key_press_time > 500)then
            key_long_long_up_handle()
        elseif(key_press_time > 150)then
            key_long_up_handle()
        elseif(key_press_time > 0)then
            key_short_up_handle()
        end

        key_press_time = 0
        key_press_event = 0
    end
end)
